<template>
  <div class="columnFlex">
    <van-form ref="form">
      <van-field
        readonly
        clickable
        name="是否代他人报备"
        is-link
        label="是否代他人报备"
        required
        :disabled="this.isEdit"
        :value="formData.isSelfFlagLabel"
        placeholder="请选择是否代他人报备"
        @click="isEdit ? (showIsSelfPicker = false) : (showIsSelfPicker = true)"
        :rules="rules.isSelfFlag"
      />
      <van-field
        v-model="formData.ctrlor"
        autocomplete="off"
        clearable
        required
        :disabled="isSelfFlag"
        name="姓名"
        label="姓名"
        placeholder="姓名"
        :rules="rules.ctrlor"
      />
      <van-field
        readonly
        clickable
        name="员工性质"
        is-link
        label="员工性质"
        required
        :value="formData.empNatureLabel"
        placeholder="请选择员工性质"
        @click="showEmpNaturePicker = true"
        :rules="rules.empNature"
      />
      <van-field
        v-model="areaValue"
        is-link
        readonly
        required
        label="涉中高风险区域"
        placeholder="请选择涉中高风险区域"
        @click="areaShow = true"
        :rules="rules.provCode"
      />
      <van-popup v-model="areaShow" round position="bottom">
        <van-cascader
          v-model="cascaderValue"
          title="请选择涉中高风险区域"
          :options="dataList"
          @close="areaShow = false"
          @change="loadData"
          @finish="onFinish"
        />
      </van-popup>
      <van-field
        readonly
        clickable
        name="健康码"
        is-link
        label="健康码"
        :value="formData.healthColorLabel"
        placeholder="请选择健康码"
        @click="showHealthColorPicker = true"
      />
      <van-field
        readonly
        clickable
        name="核酸检测频次"
        is-link
        label="核酸检测频次"
        required
        :value="formData.chkFrequencyLabel"
        placeholder="请选择核酸检测频次"
        @click="showChkFrequencyPicker = true"
        :rules="rules.chkFrequency"
      />
      <van-field
        readonly
        clickable
        name="隔离类型"
        is-link
        label="隔离类型"
        required
        :value="formData.quaraTypeLabel"
        placeholder="请选择隔离类型"
        @click="showQuaraTypePicker = true"
        :rules="rules.quaraType"
      />
      <van-field
        readonly
        clickable
        required
        :value="dateInterval"
        label="往返时间"
        placeholder="点击选择往返时间"
        :rules="rules.dateInterval"
        @click="dateShow = true"
      />
      <van-calendar
        v-model="dateShow"
        :min-date="minDate"
        :max-date="maxDate"
        :show-confirm="false"
        type="range"
        :allow-same-day="true"
        @confirm="onConfirm"
      />
      <van-field
        readonly
        clickable
        clearable
        :required="this.isQuara"
        :value="quaraDateInterval"
        label="隔离时间"
        placeholder="点击选择隔离时间"
        :rules="[
          {
            required: this.isQuara,
            message: '请选择隔离时间',
            trigger: 'change',
          },
        ]"
        @click="quaraDateShow = true"
      />
      <van-calendar
        v-model="quaraDateShow"
        :min-date="minDate"
        :max-date="maxDate"
        :show-confirm="false"
        type="range"
        :allow-same-day="true"
        @confirm="onQuaraConfirm"
        @close="onQuaraDateClose"
      >
        <template slot="footer">
          <div class="btns">
            <van-button @click="clearQuaraDate" type="danger" class="cancel-btn"
              >清除时间</van-button
            >
          </div>
        </template>
      </van-calendar>
      <van-field
        readonly
        clickable
        :required="this.isQuara"
        :value="formData.reworkDate"
        label="返岗日期"
        placeholder="点击选择返岗日期"
        :rules="[
          {
            required: this.isQuara,
            message: '请选择返岗日期',
            trigger: 'change',
          },
        ]"
        @click="reworkDateShow = true"
      />
      <van-calendar
        clearable
        v-model="reworkDateShow"
        :min-date="minDate"
        :max-date="maxDate"
        :show-confirm="false"
        @confirm="onReworkConfirm"
        @close="onReworkDateClose"
      >
        <template slot="footer">
          <div class="btns">
            <van-button
              @click="clearReworkDate"
              type="danger"
              class="cancel-btn"
              >清除时间</van-button
            >
          </div>
        </template>
      </van-calendar>
    </van-form>
    <fullLoading v-if="loading"></fullLoading>

    <div class="followerBox" style="background: #fff">
      <h5 @click="isFold = !isFold">
        <b
          >核酸检测信息（{{
            currentTest.length ? currentTest.length : 0
          }}次）</b
        >
        <p v-if="isFold">展开 <van-icon name="arrow-down" /></p>
        <p v-else>折叠 <van-icon name="arrow-up" /></p>
        <van-button
          size="mini"
          round
          type="info"
          icon="plus"
          @click="onAdd"
        ></van-button>
      </h5>
      <div v-show="!isFold" class="list">
        <div v-for="val in currentTest" :key="val.checkId" class="list-item">
          <div class="right">
            <div>
              <label>检测日期</label>
              <p>{{ val.checkDate || "-" }}</p>
            </div>
            <div>
              <label>检测结果</label>
              <p>{{ val.checkResultLabel || "-" }}</p>
            </div>
          </div>
          <van-button plain color="#ee0a24" @click="handleDelete(val)"
            >删除</van-button
          >
        </div>
        <van-empty
          v-if="!currentTest.length"
          class="custom-image"
          :image="require('../../../../assets/images/empty.png')"
          description="暂无核酸检测信息"
        />
      </div>
    </div>
    <!--  -->
    <fullscreenModal
      :modal="fullscreenModal"
      :editType="'other'"
      label="增加核酸检测信息"
      :showSave="true"
      @handleClose="fullscreenModal = false"
      @handleSave="$refs.checkItemForm.handleSave()"
    >
      <checkItem-form
        @close="fullscreenModal = false"
        @handleCheckRefresh="checkRefresh"
        ref="checkItemForm"
      />
    </fullscreenModal>
    <!-- 是否代他人报备选择 -->
    <van-action-sheet
      v-model="showIsSelfPicker"
      cancel-text="取消"
      :actions="isSelfCodeData"
      @select="onIsSelfConfirm"
    />
    <!-- 员工性质选择 -->
    <van-action-sheet
      v-model="showEmpNaturePicker"
      cancel-text="取消"
      :actions="saEmpNatureCodeData"
      @select="onEmpNaturefirm"
    />
    <!-- 健康码选择 -->
    <van-action-sheet
      v-model="showHealthColorPicker"
      cancel-text="取消"
      :actions="healthColorCodeData"
      @select="onHealthColorConfirm"
    />
    <!-- 核酸检测频次选择 -->
    <van-action-sheet
      v-model="showChkFrequencyPicker"
      cancel-text="取消"
      :actions="chkFrequencyCodeData"
      @select="onChkFrequencyConfirm"
    />
    <!-- 隔离类型选择 -->
    <van-action-sheet
      v-model="showQuaraTypePicker"
      cancel-text="取消"
      :actions="quaraTypeCodeData"
      @select="onQuaraTypeConfirm"
    />
  </div>
</template>
<script>
import {
  saveRiskAreaPerson,
  queryTestList,
  deleteTestInfo,
} from "@/api/srvAssurance/epidprevention/riskArea/riskAreaPerson";
import { queryDic, queryArea } from "@/api/common";
import checkItemForm from "./checkItemForm.vue";
export default {
  components: { checkItemForm },
  data() {
    return {
      showIsSelfPicker: false, // 是否代他人报备picker
      showEmpNaturePicker: false, // 员工性质picker
      showHealthColorPicker: false, // 健康码picker
      showChkFrequencyPicker: false, // 核酸检测频次picker
      showQuaraTypePicker: false, // 隔离类型picker
      showStartTimePicker: false, // 开始时间
      showEndTimePicker: false, // 竣工时间
      areaShow: false, //区域show
      dateShow: false, //往返日期show
      quaraDateShow: false, //隔离日期show
      reworkDateShow: false, //返岗日期show
      minDate: new Date(new Date().getFullYear() - 1, 0, 1),
      maxDate: new Date(new Date().getFullYear(), 11, 31),
      areaValue: "", //所选地区
      cascaderValue: "",
      isSelfFlag: false, //是否代报备disable
      dateInterval: "", //往返时间区间
      quaraDateInterval: "", //隔离时间区间
      reworkDate: "", //返岗日期
      isFold: true,
      formData: {
        riskAreaPersonId: "", // 涉中高风险标识
        ctrlor: "", // 姓名
        empNature: "", // 员工性质
        empNatureLabel: "",
        isSelfFlag: "", // 是否代填报
        isSelfFlagLabel: "",
        provCode: "",
        cityCode: "",
        areaCode: "",
        healthColor: "", // 健康码
        healthColorLabel: "",
        chkFrequency: "", // 核酸检测频次
        chkFrequencyLabel: "",
        quaraType: "", // 隔离类型
        quaraTypeLabel: "",
        leaveDate: "", // 出发时间
        returnDate: "", // 返回时间
        quaraStartDate: "", // 隔离开始时间
        quaraEndDate: "", // 隔离结束时间
        reworkDate: "", //返岗时间
        isAdmin: "0",
      },
      rules: {
        ctrlor: [{ required: true, message: "请输入姓名", trigger: "onBlur" }],
        provCode: [
          { required: true, message: "请选择涉中高风险地区", trigger: "blur" },
        ],
        chkFrequency: [
          {
            required: true,
            message: "请选择核酸检测频次",
            trigger: "onChange",
          },
        ],
        empNature: [
          { required: true, message: "请选择员工性质", trigger: "onChange" },
        ],
        isSelfFlag: [
          {
            required: true,
            message: "请选择是否代他人填报",
            trigger: "onChange",
          },
        ],
        quaraType: [
          {
            required: true,
            message: "请选择隔离类型",
            trigger: "onChange",
          },
        ],
        dateInterval: [
          {
            required: true,
            message: "请选择往返时间",
            trigger: "onChange",
          },
        ],
        quaraDateInterval: [
          {
            required: true,
            message: "请选择往返时间",
            trigger: "onChange",
          },
        ],
        reworkDate: [
          {
            required: true,
            message: "请选择返岗时间",
            trigger: "onChange",
          },
        ],
      },
      dataList: [],
      isSelfCodeData: [], // 是否代报备dic
      saEmpNatureCodeData: [], // 员工性质dic
      chkFrequencyCodeData: [], // 核酸检测频次dic
      healthColorCodeData: [], // 健康码dic
      quaraTypeCodeData: [], // 隔离类型dic
      currentTest: {}, //核酸检测集合
      detailCheckData: {}, //传给详情页面的核酸检测集合
      isEdit: false,
      loading: false,
      isQuara: false, //是否隔离
      fullscreenModal: false,
    };
  },
  mounted() {
    this.getDicData();
    this.getInitTree();
  },
  methods: {
    getInitTree() {
      queryArea("", "1").then((res) => {
        if (res.code == "1000") {
          let data = res.data;
          data = this.operationTree(data);
          this.dataList = data;
        }
      });
    },
    loadData(item) {
      item.loading = true;
      queryArea(item.value, Number(item.tabIndex) + 2).then((res) => {
        item.loading = false;
        if (res.code == "1000") {
          let data = res.data;
          data = this.operationTree(data);
          if (item.tabIndex == 0) {
            item.selectedOptions[0].children = data;
          } else {
            item.selectedOptions[1].children = data;
          }
        }
      });
    },
    operationTree(arr) {
      let arrData = [];
      arr.forEach((item) => {
        if (item.areaLevel > 2) {
          arrData.push({
            value: item.areaCode,
            text: item.areaName,
          });
        } else {
          arrData.push({
            value: item.areaCode,
            text: item.areaName,
            level: item.areaLevel,
            children: [],
            // loading: false,
          });
        }
      });
      return arrData;
    },
    //添加办公用品
    onAdd() {
      if (this.formData.riskAreaPersonId) {
        this.fullscreenModal = true;
        this.$refs.checkItemForm.resetForm();
        this.$refs.checkItemForm.formData.relaId =
          this.formData.riskAreaPersonId;
      } else {
        this.$Notify({ type: "warning", message: "请先保存基本信息" });
      }
    },
    // 全部选项选择完毕后，会触发 finish 事件
    onFinish(item) {
      this.areaShow = false;
      this.areaValue = item.selectedOptions
        .map((option) => option.text)
        .join("/");
      this.formData.provCode = item.selectedOptions[0].value;
      this.formData.cityCode = item.selectedOptions[1].value;
      this.formData.areaCode = item.selectedOptions[2].value;
    },
    // 获取字典数据
    getDicData() {
      // 是否代他人报备和隔离类型
      queryDic("IS_FLAG_CODE").then((res) => {
        if (res.code == "1000" && res.data) {
          this.isSelfCodeData = res.data;
        }
      });
      //员工性质
      queryDic("SA_EMP_NATURE_CODE").then((res) => {
        if (res.code == "1000" && res.data) {
          this.saEmpNatureCodeData = res.data;
        }
      });
      //核酸检测频次
      queryDic("SA_NUCLEIN_CHK_FREQUENCY_CODE").then((res) => {
        if (res.code == "1000" && res.data) {
          this.chkFrequencyCodeData = res.data;
        }
      });
      //健康码
      queryDic("SA_HEALTH_COLOR_CODE").then((res) => {
        if (res.code == "1000" && res.data) {
          this.healthColorCodeData = res.data;
        }
      });
      //隔离类型
      queryDic("SA_QUARA_TYPE_CODE").then((res) => {
        if (res.code == "1000" && res.data) {
          this.quaraTypeCodeData = res.data;
        }
      });
    },
    // 保存
    handleSave() {
      this.loading = true;
      this.$refs.form
        .validate()
        .then(async () => {
          let formData = { ...this.formData };
          if (!this.isEdit) {
            // 新增
            delete formData.riskAreaPersonId;
          }
          //新增或修改基本信息
          this.loading = false;
          let res = await saveRiskAreaPerson(formData);
          if (res.code == "1000") {
            this.$Notify({ type: "success", message: "保存成功！" });
            this.formData.riskAreaPersonId = res.data;
            this.$emit("refresh", res.data);
          } else {
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 查询原本信息
    getData(obj) {
      this.isEdit = true;
      for (var key in this.formData) {
        if (obj[key] || obj[key] === 0) {
          this.formData[key] = obj[key];
        }
      }
      this.dateInterval =
        this.formData.leaveDate + " / " + this.formData.returnDate;
      this.quaraDateInterval = this.formData.quaraStartDate
        ? this.formData.quaraEndDate
          ? this.formData.quaraStartDate + "/" + this.formData.quaraEndDate
          : ""
        : "";
      this.areaValue = obj.provName + obj.cityName + obj.areaName;
      //判断隔离类型
      this.judgeSelfFlagType(this.isEdit);
      this.judgeQuaraType();
      this.queryCheckList();
    },
    //更新核酸检测信息
    checkRefresh(data) {
      this.currentTest = data;
      this.$emit("handleCheckRefresh", data);
    },
    //查询核酸检测信息
    async queryCheckList() {
      var testStrs = { relaId: this.formData.riskAreaPersonId, busiType: "1" };
      let res = await queryTestList(testStrs);
      if (res.code == "1000" && res.data) {
        this.detailCheckData = res.data;
        this.currentTest = res.data;
        this.$emit("handleCheckRefresh", res.data);
      }
    },
    //删除核酸检测信息
    handleDelete(val) {
      this.$Dialog
        .confirm({
          title: "是否确定删除该数据？",
        })
        .then(async () => {
          var res = await deleteTestInfo([val.checkId]);
          if (res.code === 1000) {
            this.$Notify({ type: "success", message: "删除成功！" });
            this.queryCheckList();
          }
        })
        .catch(() => {});
    },
    //判断是否代填报类型
    judgeSelfFlagType(isEdit) {
      if (this.formData.isSelfFlag == 0) {
        let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
        this.formData.ctrlor = userInfo.name;
        this.isSelfFlag = true;
      } else if (!isEdit) {
        this.formData.ctrlor = "";
        this.isSelfFlag = false;
      } else {
        this.isSelfFlag = false;
      }
    },
    // 是否代他人报备选择
    onIsSelfConfirm(item) {
      this.formData.isSelfFlag = item.value;
      this.formData.isSelfFlagLabel = item.text;
      this.judgeSelfFlagType(this.isEdit);
      this.showIsSelfPicker = false;
    },
    // 员工性质选择
    onEmpNaturefirm(item) {
      this.formData.empNature = item.value;
      this.formData.empNatureLabel = item.text;
      this.showEmpNaturePicker = false;
    },
    // 健康码选择
    onHealthColorConfirm(item) {
      this.formData.healthColor = item.value;
      this.formData.healthColorLabel = item.text;
      this.showHealthColorPicker = false;
    },
    // 核酸检测频次选择
    onChkFrequencyConfirm(item) {
      this.formData.chkFrequency = item.value;
      this.formData.chkFrequencyLabel = item.text;
      this.showChkFrequencyPicker = false;
    },
    // 隔离类型选择
    onQuaraTypeConfirm(item) {
      this.formData.quaraType = item.value;
      this.formData.quaraTypeLabel = item.text;
      this.isQuara = item.value == "0" ? false : true;
      this.showQuaraTypePicker = false;
    },
    //判断隔离类型
    judgeQuaraType() {
      if (this.formData.quaraType == 0) {
        this.isQuara = false;
      } else {
        this.isQuara = true;
      }
    },
    //日期格式
    formatDate(date) {
      return `${date.getFullYear()}-${
        date.getMonth() < 9
          ? "0" + (date.getMonth() + 1)
          : "" + (date.getMonth() + 1)
      }-${date.getDate() < 10 ? "0" + date.getDate() : "" + date.getDate()}`;
    },
    // 往返时间选择
    onConfirm(date) {
      this.formData.leaveDate = this.formatDate(date[0]);
      this.formData.returnDate = this.formatDate(date[1]);
      this.dateInterval = `${this.formatDate(date[0])} / ${this.formatDate(
        date[1]
      )}`;
      this.dateShow = false;
    },
    // 隔离时间选择
    onQuaraConfirm(date) {
      this.formData.quaraStartDate = this.formatDate(date[0]);
      this.formData.quaraEndDate = this.formatDate(date[1]);
      this.quaraDateInterval = `${this.formatDate(date[0])} / ${this.formatDate(
        date[1]
      )}`;
      this.quaraDateShow = false;
    },
    // 返岗时间选择
    onReworkConfirm(date) {
      this.formData.reworkDate = this.formatDate(date);
      this.reworkDateShow = false;
    },
    // 关闭隔离日历
    onQuaraDateClose() {
      this.quaraDateShow = false;
    },
    // 关闭返岗日历
    onReworkDateClose() {
      this.reworkDateShow = false;
    },
    //清除隔离时间
    clearQuaraDate() {
      this.formData.quaraStartDate = "";
      this.formData.quaraEndDate = "";
      this.quaraDateShow = false;
      this.quaraDateInterval = "";
    },
    //清除返岗时间
    clearReworkDate() {
      this.formData.reworkDate = "";
      this.reworkDateShow = false;
    },
    // 重置表单
    resetForm() {
      this.formData = {
        riskAreaPersonId: "", // 涉中高风险标识
        ctrlor: "", // 姓名
        empNature: "", // 员工性质
        empNatureLabel: "",
        isSelfFlag: "", // 是否代填报
        isSelfFlagLabel: "",
        provCode: "",
        cityCode: "",
        areaCode: "",
        healthColor: "", // 健康码
        healthColorLabel: "",
        chkFrequency: "", // 核酸检测频次
        chkFrequencyLabel: "",
        quaraType: "", // 隔离类型
        quaraTypeLabel: "",
        leaveDate: "", // 出发时间
        returnDate: "", // 返回时间
        quaraStartDate: "", // 隔离开始时间
        quaraEndDate: "", // 隔离结束时间
        reworkDate: "", //返岗时间
        isAdmin: "0",
      };
      this.dateInterval = "";
      this.quaraDateInterval = "";
      this.reworkDate = "";
      this.isSelfFlag = false;
      this.isEdit = false;
      this.areaValue = "";
      this.currentTest = {};
      setTimeout(() => {
        this.$refs.form.resetValidation();
      });
    },
  },
};
</script>

<style scoped lang="less">
.columnFlex {
  overflow: auto;
  background: #eee;
}

.van-form {
  background: #fff;

  .photoRow {
    display: flex;
    align-items: center;
    padding: 8px 15px 0;
    box-sizing: border-box;
    justify-content: space-between;
    position: relative;

    .left {
      line-height: 25px;

      p:nth-of-type(2) {
        color: #999;
        font-size: 12px;
      }
    }
  }

  .photoRow::after {
    position: absolute;
    box-sizing: border-box;
    content: " ";
    pointer-events: none;
    right: 0.42667rem;
    bottom: 0;
    left: 0.42667rem;
    border-bottom: 0.02667rem solid #ebedf0;
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
  }

  /deep/.van-field__button a {
    color: #4eb3e9;
    font-size: 13px;
  }

  .van-tag {
    margin-right: 10px;
    line-height: 22px;
    padding: 0 8px;
  }
}

h5 {
  background: #fff;
  font-size: 13px;
  line-height: 42px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
  font-weight: normal;
  color: #666;
  position: relative;

  /deep/.van-button--mini {
    padding: 0;
    width: 18px;
    height: 18px;
  }

  p {
    position: absolute;
    right: 45px;
  }
}

.followerBox {
  background: #fff;
  border-radius: 8px;
  margin-top: 12px;
  /deep/.van-empty {
    padding: 20px 0;
    .van-empty__image {
      width: 50px;
      height: 50px;
    }
  }
  .list-item {
    background: #fff;
    display: flex;
    padding: 10px;
    box-sizing: border-box;
    align-items: center;
    img {
      width: 60px;
      height: 60px;
      margin-right: 10px;
    }
    .right {
      flex: 1;
      overflow: hidden;
      border-bottom: 1px solid #f1f1f2;
      div {
        display: flex;
        line-height: 28px;
        label {
          width: 75px;
          color: #999;
          padding: 0px 35px 0px 5px;
        }
        p {
          color: #333;
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
}

.addFormBox {
  position: relative;

  p {
    text-align: center;
    line-height: 45px;
    font-size: 14px;
    margin-bottom: 5px;
    border-bottom: 1px solid #eee;
    color: #666;
  }

  & > div {
    padding: 0 10px;
    box-sizing: border-box;
  }

  .van-icon {
    position: absolute;
    right: 10px;
    top: 10px;
  }
}

.van-button--large {
  height: 40px;
  line-height: 40px;
  width: 95%;
  margin: 10px auto;
}

// .agreementBox {
//     display: flex;
//     font-size: 11px;
//     padding: 10px;
//     box-sizing: border-box;
//     .van-checkbox {
//         margin-right: 5px;
//     }
// }
.van-dialog {
  /deep/.van-dialog__header {
    padding: 10px 0;
  }

  .centerListBox {
    height: 180px;
    padding: 0 15px;
    line-height: 32px;
    font-size: 14px;
    overflow: auto;
    box-sizing: border-box;
    margin-bottom: 10px;

    li {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      position: relative;
      padding-right: 30px;
      box-sizing: border-box;

      .van-icon {
        position: absolute;
        font-size: 18px;
        top: 5px;
        right: 0;
        color: #4eb3e9;
      }
    }
  }
}
</style>
